var bg = chrome.extension.getBackgroundPage();
var G = bg.SINA;

var Setting = JSON.parse(G.get("longSetting"));

var comment_api_url = bg.APIV.comments.to_me;
var mention_api_url = bg.APIV.comments.mentions; //获取@到我的评论
var at_mention_api_url = bg.APIV.statuses.mentions
var follower_api_url = bg.APIV.friendships.followers;
var topics_api_url = bg.APIV.search.topics;
var statuses_api_url = bg.APIV.statuses.friends_timeline; //获取最新微博
var user_timeline = bg.APIV.statuses.user_timeline;
var emotions = G.get('emotions_tpl') ? JSON.parse(G.get('emotions_tpl')) : [];
var SENDING = false;

function generateFollowerDiv(follower) {
	var data = {
		id : follower.id,
		screen_name : follower.screen_name,
		profile_image_url : follower.profile_image_url,
		followers_count : follower.followers_count,
		friends_count : follower.friends_count,
		statuses_count : follower.statuses_count,
		following : eval(follower.following) ? "取消" : "",
		verified : (follower.verified ? '<img src="/maincss/v.gif" alt="V">' : ''),
		description : follower.description,
		gender : follower.gender,
		location : follower.location
	};
	var html = G.replaceAll(followTpl, data);
	return html;
}

function generateStatusDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text : replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count,
		comments_count : statuses.comments_count,
		screen_name : statuses.user.screen_name,
		uid:statuses.user.id,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following:statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['retweeted_status'] ? generateStatusDiv(statuses.retweeted_status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};
	
	var html = G.replaceAll(zf ? statusDivZfTpl : statusDivTpl, data);
	return html;
}

var reg =  /\[.+?\]/ig;
var regat =  /@[\u4e00-\u9fa5\w\-]+/ig;
var regtopic= /#([^\#|.]+)#/ig;
var regurl = /[a-zA-z]+:\/\/[^\s^\u4e00-\u9fa5]*/ig

function replace_face(text){
	var face = text.match(reg);
	var at = text.match(regat);
	var topic = text.match(regtopic);
	var url = text.match(regurl);
	if(face && face.length){
		for(var i=0;i<face.length;i++){
			text = text.replace(face[i],emotions[face[i]]);
		}
	}
	if(at && at.length){
		at = $.unique(at);
		for(var i=0;i<at.length;i++){
			text = text.replace(new RegExp(at[i], "gm"),"<a  onMouseover='get_user_info(this,"+at[i].replace("@","")+")' onclick='showStatus(this,"+at[i].replace("@","")+")'>"+at[i]+"</a>");
		}
	}
	if(topic && topic.length){
		topic = $.unique(topic);
		for(var i=0;i<topic.length;i++){
			text = text.replace(new RegExp(topic[i], "gm"), "<a onclick='showTopic(this)'>" + topic[i] + "</a>");
		}
	}
	if(url && url.length){
		url = $.unique(url);
		for(var i=0;i<url.length;i++){
			text = text.replace(url[i],"<a target='_blank' href='"+url[i]+"'>"+url[i]+"</a>");
		}
	}
	return text;
}

function get_user_info(target,name){
	if(!$(target).attr("title") && $(target).attr("title") != "加载ing"){
		$(target).attr("title","加载ing");
		G.gets(bg.APIV.users.show, {
			screen_name : name
		}, function (rsp) {
			if (!rsp.error) {
				var title = "关注：{{friends_count}}\r\n粉丝：{{followers_count}}\r\n微博：{{statuses_count}}\r\n简介：{{description}}";
				title = G.replaceAll(title, rsp);
				$(target).attr("title",title);
			}
		});
	}
}

function generateCommentsDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text :replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count || 0,
		comments_count : statuses.comments_count || 0,
		screen_name : statuses.user.screen_name,
		uid : statuses.user.uid,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following:statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		mid : (statuses['status'] ? statuses.status.id : ''),
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['status'] ? generateCommentsDiv(statuses.status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};
	
	var html = G.replaceAll(zf ? statusNoCtrDivTpl : statusCmtDivTpl, data);
	return html;
}

/**
 *@我的评论
 */
function generateArmeCommentsDiv(statuses, zf) {
	if (statuses.deleted && statuses.deleted === "1")
		return "";
	var data = {
		id : statuses.id,
		text : replace_face(statuses.text),
		source : statuses.source,
		favorited : statuses.favorited ? '已' : '',
		reposts_count : statuses.reposts_count || 0,
		comments_count : statuses.comments_count || 0,
		screen_name : statuses.user.screen_name,
		uid : statuses.user.uid,
		followers_count : statuses.user.followers_count,
		friends_count : statuses.user.friends_count,
		statuses_count : statuses.user.statuses_count,
		following:statuses.user.following ? "取消关注" : "关注",
		verified_reason : statuses.user.verified_reason || statuses.user.description,
		mid : (statuses['status'] ? statuses.status.id : ''),
		profile_image_url : statuses.user.profile_image_url,
		created_at : G.dateDiff(new Date(statuses.created_at).getTime()),
		verified : statuses.user.verified ? '<img src="/maincss/v.gif" alt="V">' : '',
		retweeted : (statuses['status'] ? generateArmeCommentsDiv(statuses.status, true) : ''),
		media : (statuses['original_pic'] ? generatestatusMedia(statuses) : '')
	};
	
	var html = G.replaceAll(zf ? statusNoCtrDivTpl : statusAtMeCmtDivTpl, data);
	return html;
}

function generatestatusMedia(statuses) {
	var html = G.replaceAll(statusImgTpl, statuses);
	return html;
}

function showLarge(target) {
	$(target).hide().next().show();
}
function hideLarge(target) {
	$(target).hide().prev().show();
}

function doReposts(id, num) {
num = parseInt(num);
	var _wbr = $("#wb_" + id,$('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (plwrap.length) {
		plwrap.remove();
	}
	if (zfwrap.length) {
		zfwrap.remove();
	} else {
		zfwrap = G.replaceAll(zfwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(zfwrap));
		var _relist = $("#re_list_" + id,$('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_relist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.statuses.repost_timeline, {
			id : id
		}, function (rsp) {
			var _reposts = rsp.reposts;
			if (_reposts.length > 0) {
				var _list = [];
				for (var idx in _reposts) {
					var data = {
						page : 1,
						id : _reposts[idx].id,
						screen_name : _reposts[idx].user.screen_name,
						followers_count : _reposts[idx].user.followers_count,
						friends_count : _reposts[idx].user.friends_count,
						statuses_count : _reposts[idx].user.statuses_count,
						following:_reposts[idx].user.following ? "取消关注" : "关注",
						verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
						text : replace_face(_reposts[idx].text),
						created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
						profile_image_url : _reposts[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(relistTpl, data));
				}
				_relist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 20) {
					_relist.after(ReplaceMethos(G.replaceAll(zfpageTpl, {
							id : id,
							prev : 0,
							next : 2,
							clazz:"hide",
							fclazz:"hide"
						})));
				}
			} else {
				_relist.remove();
			}
		});
	}
}

function doRepostsZf(id, num) {
num = parseInt(num);
	var _wbr = $("#zf_" + id,$('div.tabpage:visible'));
	var plwrap = $(".plWrap", _wbr);
	var zfwrap = $(".zfWrap", _wbr);
	if (plwrap.length) {
		plwrap.remove();
	}
	if (zfwrap.length) {
		zfwrap.remove();
	} else {
		zfwrap = G.replaceAll(zfwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(zfwrap));
		var _relist = $("#re_list_" + id,$('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_relist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.statuses.repost_timeline, {
			id : id
		}, function (rsp) {
			var _reposts = rsp.reposts;
			if (_reposts.length > 0) {
				var _list = [];
				for (var idx in _reposts) {
					var data = {
						page : 1,
						id : _reposts[idx].id,
						screen_name : _reposts[idx].user.screen_name,
						followers_count : _reposts[idx].user.followers_count,
						friends_count : _reposts[idx].user.friends_count,
						statuses_count : _reposts[idx].user.statuses_count,
						following:_reposts[idx].user.following ? "取消关注" : "关注",
						verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
						text : replace_face(_reposts[idx].text),
						created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
						profile_image_url : _reposts[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(relistTpl, data));
				}
				_relist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 20) {
					_relist.after(ReplaceMethos(G.replaceAll(zfpageTpl, {
							id : id,
							prev : 0,
							next : 2,
							clazz:"hide",
							fclazz:"hide"
						})));
				}
			} else {
				_relist.remove();
			}
		});
	}
}

function doFavorited(target, id) {
	var text = $(target).text();
	var api_url = bg.APIV.favorites.create
		if (text !== '收藏') {
			api_url = bg.APIV.favorites.destroy;
		}
		
		G.post(api_url, {
			id : id
		}, function (rsp) {
			if (rsp.status && rsp.status.favorited) {
				$(target).text('已收藏');
			} else {
				$(target).text('收藏');
			}
		});
}

function doComment(id, num) {
num = parseInt(num);
	var _wbr = $("#wb_" + id,$('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}
	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(plwrap));
		var _pllist = $("#comments_list_" + id,$('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_pllist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.comments.show, {
			id : id
		}, function (rsp) {
			var _comments = rsp.comments;
			if (_comments.length > 0) {
				
				var _list = [];
				for (var idx in _comments) {
					var data = {
						page : 1,
						id : _comments[idx].id,
						sid : _comments[idx].status.id,
						screen_name : _comments[idx].user.screen_name,
						followers_count : _comments[idx].user.followers_count,
					friends_count : _comments[idx].user.friends_count,
					statuses_count : _comments[idx].user.statuses_count,
					following:_comments[idx].user.following ? "取消关注" : "关注",
					verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
						text : replace_face(_comments[idx].text),
						created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
						profile_image_url : _comments[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(pllistTpl, data));
				}
				_pllist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 50) {
					_pllist.after(ReplaceMethos(G.replaceAll(plpageTpl, {
							id : id,
							prev : 0,
							next : 2,
							clazz:"hide",
							fclazz:"hide"
						})));
				}
			} else {
				_pllist.remove();
			}
		});
	}
}

function doCommentCm(id, mid, screen_name) {
	var _wbr = $("#wb_" + id,$('div.tabpage:visible')).children('div.wb_r');
	var plwrap = $(">div.plWrap", _wbr);
	var zfwrap = $(">div.zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}
	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plrplwrapTpl, {
				id : id,
				mid : mid,
				screen_name : screen_name
			});
		_wbr.append(ReplaceMethos(plwrap));
	}
}

function doRePl(cid, wid, sname) {
	var rp ="回复@" + sname + ":";
	$("#plTxt_" + wid,$('div.tabpage:visible')).val(rp).focus();
	setCaretPosition($("#plTxt_" + wid,$('div.tabpage:visible'))[0], rp.length);
	$("#plTxt_warn_" + wid,$('div.tabpage:visible')).next("input").attr("onclick","send_pl_rp("+cid+","+wid+",true)");
	checkText('plTxt',wid,140);
}

function setCaretPosition(ctrl, pos){
	if(ctrl.setSelectionRange){
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function doCommentZf(id, num) {
num = parseInt(num);
	var _wbr = $("#zf_" + id,$('div.tabpage:visible'));
	var plwrap = $(".plWrap", _wbr);
	var zfwrap = $(".zfWrap", _wbr);
	if (zfwrap.length) {
		zfwrap.remove();
	}
	
	if (plwrap.length) {
		plwrap.remove();
	} else {
		plwrap = G.replaceAll(plwrapTpl, {
				id : id
			});
		_wbr.append(ReplaceMethos(plwrap));
		var _pllist = $("#comments_list_" + id,$('div.tabpage:visible'));
		if (num === 0) {
			return;
		}
		_pllist.append('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		G.gets(bg.APIV.comments.show, {
			id : id
		}, function (rsp) {
			var _comments = rsp.comments;
			if (_comments.length > 0) {
				var _list = [];
				for (var idx in _comments) {
					var data = {
						page : 1,
						id : _comments[idx].id,
						sid : _comments[idx].status.id,
						screen_name : _comments[idx].user.screen_name,
						followers_count : _comments[idx].user.followers_count,
					friends_count : _comments[idx].user.friends_count,
					statuses_count : _comments[idx].user.statuses_count,
					following:_comments[idx].user.following ? "取消关注" : "关注",
					verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
						text : replace_face(_comments[idx].text),
						created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
						profile_image_url : _comments[idx].user.profile_image_url
					};
					_list.push(G.replaceAll(pllistTpl, data));
				}
				_pllist.html(ReplaceMethos(_list.join('')));
				if (rsp.total_number > 50) {
					_pllist.after(ReplaceMethos(G.replaceAll(plpageTpl, {
							id : id,
							prev : 0,
							next : 2,
							clazz:"hide",
							fclazz:"hide"
						})));
				}
			} else {
				_pllist.remove();
			}
		});
	}
}

/**
 *关注某人
 */
function follow_one(target, id) {
	var type = $(target).text();
	var url = bg.APIV.friendships.create;
	if (type !== "关注") {
		url = bg.APIV.friendships.destroy;
	}
	
	G.post(url, {
		uid : id
	}, function (resp) {
		if (resp) {
			if (type === "关注") {
				$(target).text("取消关注");
			} else {
				$(target).text("关注");
			}
		}
	});
}

function get_comments(p, id) {
p = parseInt(p);
	if (p == 0)
		return;
	var _pageWrap = $("#pl_list_page_" + id,$('div.tabpage:visible'));
	var _pllist = $("#comments_list_" + id,$('div.tabpage:visible'));
	_pllist.html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(bg.APIV.comments.show, {
		id : id,
		page : p
	}, function (rsp) {
		var _comments = rsp.comments;
		if (_comments.length > 0) {
			var _list = [];
			for (var idx in _comments) {
				var data = {
					page : p,
					id : _comments[idx].id,
					sid : _comments[idx].status.id,
					screen_name : _comments[idx].user.screen_name,
					followers_count : _comments[idx].user.followers_count,
					friends_count : _comments[idx].user.friends_count,
					statuses_count : _comments[idx].user.statuses_count,
					following:_comments[idx].user.following ? "取消关注" : "关注",
					verified_reason : _comments[idx].user.verified_reason || _comments[idx].user.description,
					text : replace_face(_comments[idx].text),
					created_at : G.dateDiff(new Date(_comments[idx].created_at).getTime()),
					profile_image_url : _comments[idx].user.profile_image_url
				};
				_list.push(G.replaceAll(pllistTpl, data));
			}
			_pllist.html(ReplaceMethos(_list.join('')));
		}
		var next = p;
		var totalPage = Math.ceil(rsp.total_number/50);
		if (p != totalPage) {
			next = p + 1;
		}
		_pageWrap.replaceWith(ReplaceMethos(G.replaceAll(plpageTpl, {
				id : id,
				prev : p - 1,
				next : next,
				clasz:((p == totalPage) ? "hide" :""),
				clazz:((p == 1) ? "hide" :""),
				fclazz:((p == 1) ? "hide" :""),
				first:1
			})));
	});
}

function get_reposts(p, id) {
p = parseInt(p);
	if (p == 0)
		return;
	var _pageWrap = $("#re_list_page_" + id,$('div.tabpage:visible'));
	var _relist = $("#re_list_" + id,$('div.tabpage:visible'));
	_relist.html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(bg.APIV.statuses.repost_timeline, {
		id : id,
		page : p
	}, function (rsp) {
		var _reposts = rsp.reposts;
		if (_reposts.length > 0) {
			
			var _list = [];
			for (var idx in _reposts) {
				var data = {
					page : p,
					id : _reposts[idx].id,
					screen_name : _reposts[idx].user.screen_name,
					followers_count : _reposts[idx].user.followers_count,
					friends_count : _reposts[idx].user.friends_count,
					statuses_count : _reposts[idx].user.statuses_count,
					following:_reposts[idx].user.following ? "取消关注" : "关注",
					verified_reason : _reposts[idx].user.verified_reason || _reposts[idx].user.description,
					text : replace_face(_reposts[idx].text),
					created_at : G.dateDiff(new Date(_reposts[idx].created_at).getTime()),
					profile_image_url : _reposts[idx].user.profile_image_url
				};
				_list.push(G.replaceAll(relistTpl, data));
			}
			_relist.html(ReplaceMethos(_list.join('')));
		}
		var next = p;
		var totalPage = Math.ceil(rsp.total_number/20);
		if (p != totalPage) {
			next = p + 1;
		}
		_pageWrap.replaceWith(ReplaceMethos(G.replaceAll(zfpageTpl, {
				id : id,
				prev : p - 1,
				next : next,
				clasz:((p == totalPage) ? "hide" :""),
				clazz:((p == 1) ? "hide" :""),
				fclazz:((p == 1) ? "hide" :""),
				first:1
			})));
	});
}

function checkText(type, id, count) {
	var v = $.trim($('#' + type + "_" + id).val());
	var left = calWbText(v, count);
	if (left >= 0) {
		$('#' + type + "_warn_" + id).html('还能输入<em>' + left + '</em>字');
	} else {
		$('#' + type + "_warn_" + id).html('已超出<em style="color:red;">' + Math.abs(left) + '</em>字');
	}
	return left >= 0 && v;
}
function calWbText(text, count) {
	var cLen = 0;
	var matcher = text.match(/[^\x00-\xff]/g),
	wlen = (matcher && matcher.length) || 0;
	return Math.floor((count * 2 - text.length - wlen) / 2);
}

/**
 *转发
 */
function send_zf(id, pl) {
	if(SENDING) return;
	var status = $.trim($("#zfTxt_" + id,$('div.tabpage:visible')).val());
	var color = "";
	if (!pl)
		color = $("#zfTxt_warn_" + id + " em",$('div.tabpage:visible')).prop("style").color;
	if (color != 'red') {
		if (pl)
			status = pl;
		
		SENDING = true;
		G.post(bg.APIV.statuses.repost, {
			id : id,
			is_comment : $("#zf_pl_" + id,$('div.tabpage:visible')).prop("checked") ? 3 : 0,
			status : status ? status : ""
		}, function (rsp) {
			if (!rsp.error) {
				G.showMsgNotification("操作成功!");
				if (!pl) {
					$("#home_zfWrap_" + id,$('div.tabpage:visible')).remove();
				} else {
					$("#home_plWrap_" + id,$('div.tabpage:visible')).remove();
				}
				
			}
			
			SENDING = false;
		});
	}
}

/**
 *评论微博
 */
function send_pl(id) {
	if(SENDING) return;
	var status = $.trim($("#plTxt_" + id,$('div.tabpage:visible')).val());
	var color = $("#plTxt_warn_" + id + " em",$('div.tabpage:visible')).prop("style").color;
	if (status && color != 'red') {
		SENDING = true;
		G.post(bg.APIV.comments.create, {
			id : id,
			comment : status ? status : ""
		}, function (rsp) {
			if (!rsp.error) {
				if ($("#pl_zf_" + id,$('div.tabpage:visible')).prop("checked")) {
					SENDING = false;
					send_zf(id, status);
				} else {
					G.showMsgNotification("操作成功!");
					$("#home_plWrap_" + id,$('div.tabpage:visible')).remove();
					SENDING = false;
				}
			}else{
				SENDING = false;
			}
		});
	}
}
/**
 *回复评论
 */
function send_pl_rp(id, mid,target) {
	if(SENDING) return;
	var status = $.trim($("#plTxt_" + (target ? mid : id),$('div.tabpage:visible')).val());
	var color = $("#plTxt_warn_" + (target ? mid : id) + " em",$('div.tabpage:visible')).prop("style").color;
	if (status && color != 'red') {
		SENDING = true;
		G.post(bg.APIV.comments.reply, {
			cid : id,
			id : mid,
			comment : status ? status : "",
			without_mention : 1
		}, function (rsp) {
			if (!rsp.error) {
				if ($("#pl_zf_" + (target ? mid : id),$('div.tabpage:visible')).prop("checked")) {
					SENDING = false;
					send_zf(mid, status);
				} else {
					G.showMsgNotification("操作成功!");
				}
				if(target){
					$("#plTxt_warn_" + mid,$('div.tabpage:visible')).next("input").attr("onclick","send_pl("+mid+")");
					$("#plTxt_" + mid,$('div.tabpage:visible')).val("");
				}else{
					$("#home_plWrap_" + id,$('div.tabpage:visible')).remove();
				}
			}
			SENDING = false;
		});
	}
}

function doDestroy(id) {
	G.post(bg.APIV.comments.destroy, {
		cid : id
	}, function (rsp) {
		if (!rsp.error) {
			G.showMsgNotification("操作成功!");
			$("#wb_" + id,$('div.tabpage:visible')).remove();
		}
	});
}

function doane(event) {
	e = event ? event : window.event;
	e.stopPropagation();
	e.preventDefault();
}

var imgTarget,infoTarget;
function showInfo(target){
	if(target && target!=imgTarget){
		imgTarget = target;
		$(".user_info,.info_unset").hide();
		$(target).next().show();
		var info = $(target).parent().next();
		infoTarget = info[0];
		info.unbind().mouseout(function(event){
					if(event.relatedTarget.nodeName != "P" && event.relatedTarget != imgTarget && event.relatedTarget != infoTarget){
						hideInfo(this);
					}
			});
		info.fadeIn();
	}
}
function hideInfo(target){
	$(target).prev().children("a").hide();
	$(target).fadeOut();
	imgTarget =null;
	infoTarget =null;
}


function showFace(target){
	console.log($(target).closest('div.btn').prev().children('textarea'));
	var showid = $(target).closest('div.btn').prev().children('textarea').attr('id');
	var wrap =$("#faceWraps");
	if (wrap.html() == ""){
		wrap.html(FACE_HTML);
	}
	wrap.children().unbind('click').click(function () {
		insertFace(showid, $(this).attr("title"));
	});
		
	var offset = $(target).offset();
	wrap.css({left:offset.left-70,top:offset.top-70});
	wrap.show();
	
	doane();
	$(document.body).unbind('click').click(function (e) {
		wrap.hide();
	});
	$(".tabpage").unbind('click').scroll(function (e) {
		wrap.hide();
	});
}

function insertFace(showid, text) {
	console.log(showid);
	var obj = document.getElementById(showid);
	selection = document.selection;
	checkFocus(showid);
	var opn = obj.selectionStart + 0;
	obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
	var arra = showid.split("_");
	checkText(arra[0],arra[1], 140);
}

function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function checkFocus(target) {
	var obj = document.getElementById(target);
	if (obj !=null && !obj.hasfocus) {
		obj.focus();
	}
}

function imgEror(target){
	target.src='/maincss/404.png';
}

function showStatus(target,scname){
	var scname = scname||$(target).text();
	if($.trim(scname)){
		$("#tabpage_info").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
		$("#tabHeader_info").text(scname).show().click();
		$("#tabHeader_topic").hide();
		$("#tabpage_topic").empty();
		G.gets(user_timeline, {screen_name:$.trim(scname)}, function (rsp) {
			var status_html = '';
			var _status = rsp.statuses;
			for (var idx in _status) {
				status_html += generateStatusDiv(_status[idx]);
			}
			var $status_html = ReplaceMethos(status_html);
			$("#tabpage_info").html($status_html);
			if(rsp.total_number > 50){
				$("#tabpage_info").append(ReplaceMethos(G.replaceAll(pageTpl, {
					id : "userweibo",
					type:$.trim(scname),
					prev : 0,
					next : 2,
					clazz:"hide",
					fclazz:"hide",
					method:"userStatus"
				})));
			}
		});
	}
}

function get_userStatus(type,p){
	p = parseInt(p);
	var request = {
		'count' : 50,
		'page': p,
		'screen_name':type
	};
	$("#tabpage_info").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(user_timeline, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_info").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number/50);
		if (p != totalPage) {
			next = p + 1;
		}
		if(rsp.total_number > 50){
			$("#tabpage_info").append(ReplaceMethos(G.replaceAll(pageTpl, {
				id : "userweibo",
				type:type,
				prev : p-1,
				next : next,
				clasz:((p == totalPage) ? "hide" :""),
				clazz:((p == 1) ? "hide" :""),
				fclazz:((p == 1) ? "hide" :""),
				first:1,
				method:"userStatus"
			})));
		}
	});
}

function getTopic(topic) {
	$("#tabHeader_info").hide();
	$("#tabpage_info").empty();
	$("#tabHeader_topic").attr("title", "话题:" + topic).show().click();
	$("#tabpage_topic").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(topics_api_url, {
		'q' : topic
	}, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		if(status_html){
			$("#tabpage_topic").html(ReplaceMethos(status_html));
		}else{
			$("#tabpage_topic").html("没有找到相关微博！");
		}
		if (rsp.total_number > 10) {
			$("#tabpage_topic").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gstopic",
						prev : 0,
						next : 2,
						clazz : "hide",
						fclazz : "hide",
						method : "topic",
						type : topic
					})));
		}
	});
}

function get_topic(type, p) {
	p = parseInt(p);
	var request = {
		'count' : 10,
		'page' : p,
		'q' : type
	};
	$("#tabpage_topic").html('<div style="text-align:center;"><img src="/waiting.gif"/></div>');
	G.gets(topics_api_url, request, function (rsp) {
		var status_html = '';
		var _status = rsp.statuses;
		for (var idx in _status) {
			status_html += generateStatusDiv(_status[idx]);
		}
		$("#tabpage_topic").html(ReplaceMethos(status_html));
		var next = p;
		var totalPage = Math.ceil(rsp.total_number / 10);
		if (p != totalPage) {
			next = p + 1;
		}
		if (rsp.total_number > 10) {
			$("#tabpage_topic").append(ReplaceMethos(G.replaceAll(pageTpl, {
						id : "gstopic",
						prev : p - 1,
						next : next,
						clasz : ((p == totalPage) ? "hide" : ""),
						clazz : ((p == 1) ? "hide" : ""),
						fclazz : ((p == 1) ? "hide" : ""),
						first : 1,
						method : "topic",
						type:type
					})));
		}
	});
}

function showTopic(target) {
	var topic = $(target).text();
	topic = topic.replace(new RegExp("#", "gm"),'');
	getTopic(topic);
}

var Methods = {
	doComment:doComment,
	doCommentZf:doCommentZf,
	doFavorited:doFavorited,
	doReposts:doReposts,
	doRepostsZf:doRepostsZf,
	follow_one:follow_one,
	hideLarge:hideLarge,
	showLarge:showLarge,
	showInfo:showInfo,
	get_user_info:get_user_info,
	imgEror:imgEror,
	doDestroy:doDestroy,
	doCommentCm:doCommentCm,
	checkText:checkText,
	send_zf:send_zf,
	send_pl:send_pl,
	send_pl_rp:send_pl_rp,
	doRePl:doRePl,
	get_reposts:get_reposts,
	get_comments:get_comments,
	get_topic:get_topic,
	showFace:showFace,
	get_userStatus:get_userStatus,
	showStatus:showStatus,
	showTopic:showTopic
};

function RefactorEvent(target,etype,mtName,params){
	var mths = Methods[mtName];
	$(target).on(etype,function(){
		if(params){
			if(params.length==1){
				if(params[0] == "this"){
					mths.call(this,this);
				}else{
					mths.call(this,params[0]);
				}
			}
			if(params.length==2){
				if(params[0] == "this"){
					mths.call(this,this,params[1]);
				}else{
					mths.call(this,params[0],params[1]);
				}
			}
			if(params.length==3){
				if(params[0] == "this"){
					mths.call(this,this,params[1],params[2]);
				}else{
					mths.call(this,params[0],params[1],params[2]);
				}
			}
		}else{
			mths.call(this);
		}
	});
}

function MethosR(evt,html){
	var $html = $(html);
	$.each(evt,function(k,v){
		$("["+v+"]",$html).each(function(){
			var clk = $(this).attr(v);
			var mt = clk.substring(0,clk.indexOf("("));
			var params = clk.substring(clk.indexOf("(")+1,clk.length-1).split(',');
			RefactorEvent(this,v.substring(2,v.length),mt,params);
			$(this).removeAttr(v);
		});
	});
	return $html;
}

function ReplaceMethos(html){
	return MethosR(["onclick","onmouseover","onerror","onkeyup"],html);
}


$(function () {
	var status_flag = G.get('status_flag');
	var cmt_flag = G.get('mention_cmt_flag');
	var fol_flag = G.get('follower_flag');
	var men_st_flag = G.get('mention_status_flag');
	
	var status_num = cmt_num = fol_num = dm_num = men_num = atcmt_num = 0;
	//最新微博
	status_num = parseInt(G.get('status'));
	if (status_num > 0) {
		var request = {
			'count' : (status_num > 100 ? 100 : status_num)
		};
		G.gets(statuses_api_url, request, function (rsp) {
			var status_html = '';
			var _status = rsp.statuses;
			for (var idx in _status) {
				status_html += generateStatusDiv(_status[idx]);
			}
			$("#tabpage_status").html(ReplaceMethos(status_html));
			G.set('status',0);
		});
	} else {
		$('#tabpage_status,#tabHeader_status').remove();
	}
	
	//评论
	
	cmt_num = parseInt(G.get('cmt'));
	if (cmt_num > 0) {
		var request = {
			'page' : 1,
			'count' : cmt_num
		};
		G.gets(comment_api_url, request, function (rsp) {
			var cmt_html = '';
			var _comments = rsp.comments;
			for (var idx in _comments) {
				cmt_html += generateCommentsDiv(_comments[idx]);
			}
			$("#tabpage_cmts").html(ReplaceMethos(cmt_html));
			G.set('cmt',0);
		});
	} else {
		$('#tabpage_cmts,#tabHeader_cmts').remove();
	}
	
	//@我的评论
	
	men_num = parseInt(G.get('mention_cmt'));
	if (men_num > 0) {
		var request = {
			'page' : 1,
			'count' : men_num
		};
		G.gets(mention_api_url, request, function (rsp) {
			var cmt_html = '';
			var _comments = rsp.comments;
			for (var idx in _comments) {
				cmt_html += generateArmeCommentsDiv(_comments[idx]);
			}
			$("#tabpage_atme").html(ReplaceMethos(cmt_html));
			G.set('mention_cmt',0);
		});
	} else {
		$('#tabpage_atme,#tabHeader_atme').remove();
	}
	
	//@我的微博
	atcmt_num = parseInt(G.get('mention_status'));
	if (atcmt_num > 0) {
		var request = {
			'page' : 1,
			'count' : atcmt_num
		};
		G.gets(at_mention_api_url, request, function (rsp) {
			var cmt_html = '';
			var _statuses = rsp.statuses;
			for (var idx in _statuses) {
				cmt_html += generateStatusDiv(_statuses[idx]);
			}
			$("#tabpage_atmewb").html(ReplaceMethos(cmt_html));
			G.set('mention_status',0);
		});
	} else {
		$('#tabpage_atmewb,#tabHeader_atmewb').remove();
	}
	
	fol_num = parseInt(G.get('follower'));
	if (fol_num > 0) {
		var request = {
			'uid' : G.get('uid'),
			'cursor' : 0,
			'count' : fol_num
		};
		G.gets(follower_api_url, request, function (rsp) {
			var follower_list = rsp['users'];
			var follower_html = '';
			for (var idx in follower_list) {
				follower_html += generateFollowerDiv(follower_list[idx]);
			}
			$("#tabpage_fans").html(ReplaceMethos(follower_html));
			G.set('follower',0);
		});
	} else {
		$('#tabpage_fans,#tabHeader_fans').remove();
	}
	
	chrome.browserAction.setTitle({title : "Godson分享(&G)"});
	chrome.browserAction.setBadgeBackgroundColor({color : [0, 0, 0, 255]});
	chrome.browserAction.setBadgeText({text : ""});
	
	$(".return").click(function () {
		window.location.replace('popup.html');
	});
	
	setTimeout(function(){
		G.clearCounts();
	},1000);
	
	$("#tabHeader_info").dblclick(function(){
		$("ul>li:first").click();
		$(this).hide();
		$("#tabpage_info").empty();
	});
	
	$("#tabHeader_topic").dblclick(function () {
		$("ul>li:first").click();
		$(this).hide();
		$("#tabpage_topic").empty();
		$("#topicInput").val("")
	});
});
